<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>图片懒加载</title>
	<style>
		img {
			display: block;
			width: 800px;
			height: 450px;
			margin-bottom: 20px;
			MARGIN-RIGHT: auto;
			MARGIN-LEFT: auto;
		}
	</style>
</head>
<body>
	<img data-src="https://www.wailian.work/images/2019/02/28/Javaee-tutorial-admin-min.png"/>
	<img data-src="https://www.wailian.work/images/2019/02/28/SpringMVC-Mybatis-Shiro-redis-0.2-min-min.png"/>
	<img data-src="https://www.wailian.work/images/2019/02/28/smart-authority-min-min.png"/>
	<img data-src="https://www.wailian.work/images/2019/02/28/MyBatis-Spring-Boot-min.png"/>
	<img data-src="https://www.wailian.work/images/2019/02/28/any-video-min-min.jpg"/>
	<img data-src="https://www.wailian.work/images/2019/02/28/mybatis-generator-gui-min-min.png"/>
	<img data-src="https://www.wailian.work/images/2019/02/28/any-chat-min-min.png"/>
	<img data-src="https://www.wailian.work/images/2019/02/28/iBase4J-SpringBoot-min-min.png"/>
	<img data-src="https://www.wailian.work/images/2019/02/28/renren-fast-menus-min.png"/>
	<img data-src="https://www.wailian.work/images/2019/02/28/JavaQuarkBBS-min-min.jpg"/>
</body>
<script>
	var imgs = document.querySelectorAll('img');
	//用来判断bound.top<=clientHeight的函数，返回一个bool值
	function isIn(el) {
		var bound = el.getBoundingClientRect();
		var clientHeight = window.innerHeight;
		return bound.top <= clientHeight;
	}
	//检查图片是否在可视区内，如果不在，则加载
	function check() {
		Array.from(imgs).forEach(function(el){
			if(isIn(el)){
				loadImg(el);
			}
		})
	}
	function loadImg(el) {
		if(!el.src){
			var source = el.dataset.src;
			el.src = source;
		}
	}
	window.onload = window.onscroll = function () { //onscroll()在滚动条滚动的时候触发
		check();
	}
</script>
</html>